<script lang="ts" setup>
import type { RoomApi } from '#/api/spa/room';

import { computed, ref, h, onMounted, watch, nextTick } from 'vue';
import { $t } from '#/locales';

import { Plus } from '@vben/icons';
import {
  Button,
  Tabs,
  Checkbox,
  Input,
  Textarea,
  Select,
  RadioGroup,
  CheckboxGroup,
  DatePicker,
} from 'ant-design-vue';
import { ImageUpload, FileUpload } from '#/components/upload';
import type { OnActionClickParams } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { useRoomEnvironmentGridEditColumns } from '../data';
import { getRoomEnvironmentListByRoomId } from '#/api/spa/room';

const props = defineProps<{
  roomId?: number; // 房间ID（主表的关联字段）
}>();

/** 表格操作按钮的回调函数 */
function onActionClick({
  code,
  row,
}: OnActionClickParams<RoomApi.RoomEnvironment>) {
  switch (code) {
    case 'delete': {
      onDelete(row);
      break;
    }
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    columns: useRoomEnvironmentGridEditColumns(onActionClick),
    border: true,
    showOverflow: true,
    autoResize: true,
    keepSource: true,
    rowConfig: {
      keyField: 'id',
    },
    pagerConfig: {
      enabled: false,
    },
    toolbarConfig: {
      enabled: false,
    },
  },
});

/** 添加SPA房间环境监控 */
const onAdd = async () => {
  await gridApi.grid.insertAt({} as RoomApi.RoomEnvironment, -1);
};

/** 删除SPA房间环境监控 */
const onDelete = async (row: RoomApi.RoomEnvironment) => {
  await gridApi.grid.remove(row);
};

/** 提供获取表格数据的方法供父组件调用 */
defineExpose({
  getData: (): RoomApi.RoomEnvironment[] => {
    const data = gridApi.grid.getData() as RoomApi.RoomEnvironment[];
    const removeRecords =
      gridApi.grid.getRemoveRecords() as RoomApi.RoomEnvironment[];
    const insertRecords =
      gridApi.grid.getInsertRecords() as RoomApi.RoomEnvironment[];
    return data
      .filter((row) => !removeRecords.some((removed) => removed.id === row.id))
      .concat(insertRecords.map((row: any) => ({ ...row, id: undefined })));
  },
});

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.roomId,
  async (val) => {
    if (!val) {
      return;
    }
    await nextTick();
    await gridApi.grid.loadData(
      await getRoomEnvironmentListByRoomId(props.roomId!),
    );
  },
  { immediate: true },
);
</script>

<template>
  <Grid class="mx-4">
    <template #monitorTime="{ row }">
      <DatePicker
        v-model:value="row.monitorTime"
        :showTime="true"
        format="YYYY-MM-DD HH:mm:ss"
        valueFormat="x"
      />
    </template>
    <template #temperature="{ row }">
      <Input v-model:value="row.temperature" />
    </template>
    <template #humidity="{ row }">
      <Input v-model:value="row.humidity" />
    </template>
    <template #airQuality="{ row }">
      <Input v-model:value="row.airQuality" />
    </template>
    <template #noiseLevel="{ row }">
      <Input v-model:value="row.noiseLevel" />
    </template>
    <template #lightingLevel="{ row }">
      <Input v-model:value="row.lightingLevel" />
    </template>
    <template #waterTemperature="{ row }">
      <Input v-model:value="row.waterTemperature" />
    </template>
    <template #waterQuality="{ row }">
      <Input v-model:value="row.waterQuality" />
    </template>
    <template #environmentMetrics="{ row }">
      <Input v-model:value="row.environmentMetrics" />
    </template>
    <template #scope="{ row }">
      <Input v-model:value="row.scope" />
    </template>
    <template #scoperef="{ row }">
      <Input v-model:value="row.scoperef" />
    </template>
    <template #storeId="{ row }">
      <Input v-model:value="row.storeId" />
    </template>
  </Grid>
  <div class="-mt-4 flex justify-center">
    <Button
      :icon="h(Plus)"
      type="primary"
      ghost
      @click="onAdd"
      v-access:code="['spa:room:create']"
    >
      {{ $t('ui.actionTitle.create', ['SPA房间环境监控']) }}
    </Button>
  </div>
</template>
